<!-- 用户列表 -->
<template>
    <div class="box">
        <div class="top">
            <div class="back" @click="$router.back()">
                <svgIcon iconName="icon-fanhui" font-size="40px"></svgIcon>
            </div>
            <div class="top_gz" :class="{ top_active: activeTab === 'following' }" @click="switchTab('following')">关注</div>
            <div class="top_fs" :class="{ top_active: activeTab === 'followers' }" @click="switchTab('followers')">粉丝</div>
        </div>
        <div class="content">
          <p v-if="(activeTab === 'following' && followingUsers.length > 0) || (activeTab === 'followers' && followersUsers.length > 0)">
            {{ activeTab === 'following' ? '我的关注' : '我的粉丝' }}
          </p>
          <div class="cont_list">
            <div v-for="user in activeTab === 'following' ? followingUsers : followersUsers" :key="user.user_id" class="item" @click="goToUserDetail(user.user_id)">
              <img class="item_pic" :src="user.avatar_url || pic" />
              <div class="item_name">{{ user.nickname || '未设置名称'}}</div>
              <div v-if="activeTab === 'following'" class="item_info" :class="{ 'info_active': isMutualFollow(user.user_id) }">
                {{ isMutualFollow(user.user_id) ? '互相关注' : '已关注' }}
              </div>
              <div v-else class="item_info" :class="{ 'info_active': !isMutualFollow(user.user_id) }">
                {{ isMutualFollow(user.user_id) ? '互相关注' : '回关' }}
              </div>
            </div>
          </div>
          <div v-if="showRecommend" class="bg"></div>
          <div v-if="showRecommend" class="user_like">你可能感兴趣的 <span style="margin-left: 420px;" @click="closeRecommend">关闭</span></div>
          <div v-if="showRecommend" class="cont_list">
            <div v-for="user in randomUsers" :key="user.user_id" class="item" @click="goToUserDetail(user.user_id)">
              <img class="item_pic" :src="user.avatar_url || pic" />
              <div class="item_name">{{ user.nickname || '未设置名称'}}</div>
              <div class="item_info" :class="{ 'info_active': isMutualFollow(user.user_id) }">
                {{ isMutualFollow(user.user_id) ? '互相关注' : (myFollowingList.includes(user.user_id) ? '已关注' : '关注') }}
              </div>
            </div>
          </div>
        </div>
    </div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import pic from '../../assets/czq/pic.png'
import { useRouter, useRoute } from 'vue-router';

const router = useRouter();
const route = useRoute();
const randomUsers = ref([]);
const followingUsers = ref([]);
const followersUsers = ref([]);
const showRecommend = ref(true);
const activeTab = ref('following');
const myFollowingList = ref([]); // 存储当前用户的关注列表
const myFollowersList = ref([]); // 存储当前用户的粉丝列表

// 切换标签
const switchTab = (tab) => {
    activeTab.value = tab;
    if (tab === 'following' && followingUsers.value.length === 0) {
        getFollowingList();
    } else if (tab === 'followers' && followersUsers.value.length === 0) {
        getFollowersList();
    }
};

// 跳转到用户详情页
const goToUserDetail = (userId) => {
    router.push({
        path: '/usercont',
        query: { userId: userId }
    });
};

// 关闭推荐
const closeRecommend = () => {
    showRecommend.value = false;
};

// 获取关注列表
const getFollowingList = async () => {
    try {
        const userId = localStorage.getItem('user_id');
        if (!userId) {
            console.error('未找到用户ID');
            return;
        }
        const response = await axios.get(`http://1.14.98.17:8765/api/profile/${userId}/following`);
        if (response.data.success) {
            const followingPromises = response.data.data.following.map(async (followingId) => {
                const userResponse = await axios.get(`http://1.14.98.17:8765/api/users/${followingId}`);
                return userResponse.data.success ? userResponse.data.data : null;
            });
            
            const users = await Promise.all(followingPromises);
            followingUsers.value = users.filter(user => user !== null);
        }
    } catch (error) {
        console.error('获取关注列表失败:', error);
    }
};

// 获取粉丝列表
const getFollowersList = async () => {
    try {
        const userId = localStorage.getItem('user_id');
        if (!userId) {
            console.error('未找到用户ID');
            return;
        }
        const response = await axios.get(`http://1.14.98.17:8765/api/profile/${userId}/followers`);
        if (response.data.success) {
            const followersPromises = response.data.data.followers.map(async (followerId) => {
                const userResponse = await axios.get(`http://1.14.98.17:8765/api/users/${followerId}`);
                return userResponse.data.success ? userResponse.data.data : null;
            });
            
            const users = await Promise.all(followersPromises);
            followersUsers.value = users.filter(user => user !== null);
        }
    } catch (error) {
        console.error('获取粉丝列表失败:', error);
    }
};

// 获取随机用户数据
const getRandomUsers = async () => {
    try {
        const response = await axios.get('http://1.14.98.17:8765/api/users');
        if (response.data.success) {
            const shuffled = response.data.data.sort(() => 0.5 - Math.random());
            randomUsers.value = shuffled.slice(0, 15);
        }
    } catch (error) {
        console.error('获取用户数据失败:', error);
    }
};

// 获取当前用户的关注列表
const getMyFollowingList = async () => {
    try {
        const userId = localStorage.getItem('user_id');
        if (!userId) {
            console.error('未找到用户ID');
            return;
        }
        const response = await axios.get(`http://1.14.98.17:8765/api/profile/${userId}/following`);
        if (response.data.success) {
            myFollowingList.value = response.data.data.following;
        }
    } catch (error) {
        console.error('获取关注列表失败:', error);
    }
};

// 获取当前用户的粉丝列表
const getMyFollowersList = async () => {
    try {
        const userId = localStorage.getItem('user_id');
        if (!userId) {
            console.error('未找到用户ID');
            return;
        }
        const response = await axios.get(`http://1.14.98.17:8765/api/profile/${userId}/followers`);
        if (response.data.success) {
            myFollowersList.value = response.data.data.followers;
        }
    } catch (error) {
        console.error('获取粉丝列表失败:', error);
    }
};

// 判断是否互相关注
const isMutualFollow = (userId) => {
    // 检查用户是否同时存在于关注列表和粉丝列表中
    return myFollowingList.value.includes(userId) && myFollowersList.value.includes(userId);
};

onMounted(() => {
    // 检查URL参数，自动切换到相应的标签
    const tabParam = route.query.tab;
    if (tabParam === 'followers') {
        activeTab.value = 'followers';
        getFollowersList();
    } else {
        // 默认显示关注列表
        activeTab.value = 'following';
        getFollowingList();
    }
    
    getRandomUsers();
    getMyFollowingList();
    getMyFollowersList(); // 获取当前用户的粉丝列表
});
</script>
<style lang="less" scoped>
.box {
    width: 100%;
    min-height: 100vh;
    background-color: #fff;
    .top {
      width: 100%;
      height: 100px;
      font-size: 32px;
      display: flex;
      align-items: center;
      background-color: #fff;
      position: fixed;
      top: 0;
      left: 0;
      z-index: 10;
      .back {
        width: 100px;
        height: 100%;
        line-height: 100px;
        text-align: center;
      }
      .top_gz {
        margin-left: 180px;
        width: 80px;
        height: 70px;
        text-align: center;
        color: gray;
        line-height: 70px;
        font-size: 32px;
      }    
      .top_fs {
        margin-left: 20px;
        width: 80px;
        height: 70px;
        text-align: center;
        color: gray;
        line-height: 70px;
        font-size: 32px;
      }
      .top_active {
        border-bottom: 8px solid red;
        color: #000;
      }
    }
    .content {
      margin-top: 100px;
      width: 100%;
      p {
        background-color: #fff;
        color: gray;
        padding-left: 30px;
      }
      .bg {
        width: 100%;
        height: 50px;
        background-color: #f5f5f5;
      }
      .user_like {
        padding: 0 30px;
        height: 50px;
        line-height: 75px;
      }
      .cont_list {
        width: 100%;
        padding: 0 30px;
        .item {
          width: 100%;
          height: 150px;
          display: flex;
          align-items: center;
          justify-content: space-between;
            .item_pic {
              display: block;
              width: 80px;
              height: 80px;
              border-radius: 50%;
            }
            .item_name {
              width: 400px;
              font-size: 32px;
              color: #000;
            }
            .item_info {
              width: 130px;
              text-align: center;
              height: 40px;
              line-height: 40px;
              border: 1px solid gray;
              border-radius: 30px;
            }
            .info_active {
              border: 1px solid red;
              color: red;
            }
        }
      }
    }
}
</style>